<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Server } from '../entity'
import type { ServerQuery } from '../domain'
import * as serverApi from '../api'

// 查询参数
const queryParams = ref<ServerQuery>({
  page: 1,
  pageSize: 10,
  name: ''
})

// 表格数据
const tableData = ref<Server[]>([])
const total = ref(0)
const loading = ref(false)

// 表格选中项
const selectedRows = ref<Server[]>([])

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<Partial<Server>>({})
const formMode = ref<'add' | 'edit'>('add')

// 加载表格数据
const loadData = async () => {
  try {
    loading.value = true
    const result = await serverApi.getByPage(queryParams.value)
    tableData.value = result.list
    total.value = result.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.value.page = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  queryParams.value = {
    page: 1,
    pageSize: 10,
    name: ''
  }
  loadData()
}

// 分页变化
const handlePageChange = (page: number) => {
  queryParams.value.page = page
  loadData()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  queryParams.value.pageSize = size
  queryParams.value.page = 1
  loadData()
}

// 选择行变化
const handleSelectionChange = (rows: Server[]) => {
  selectedRows.value = rows
}

// 打开新增对话框
const handleAdd = () => {
  formMode.value = 'add'
  dialogTitle.value = '新增服务器'
  formData.value = {}
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row: Server) => {
  formMode.value = 'edit'
  dialogTitle.value = '编辑服务器'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!formData.value.name || !formData.value.host || !formData.value.port || !formData.value.username) {
      ElMessage.warning('请填写必填项')
      return
    }

    // 检查名称是否存在
    const exists = await serverApi.checkNameExists(
      formData.value.name!,
      formMode.value === 'edit' ? formData.value.id : undefined
    )
    if (exists) {
      ElMessage.warning('服务器名称已存��')
      return
    }

    if (formMode.value === 'add') {
      await serverApi.add(formData.value as Omit<Server, 'id' | 'createTime' | 'updateTime'>)
    } else {
      await serverApi.update(formData.value as Server)
    }

    ElMessage.success(`${formMode.value === 'add' ? '新增' : '编辑'}成功`)
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 删除
const handleDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm('确认删除选中的服务器吗？', '提示', {
      type: 'warning'
    })
    await serverApi.remove(id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的服务器')
    return
  }

  try {
    await ElMessageBox.confirm('确认删除选中的服务器吗？', '提示', {
      type: 'warning'
    })
    await serverApi.batchRemove(selectedRows.value.map(row => row.id))
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="server-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="服务器名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入服务器名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="服务器名称" prop="name" />
      <el-table-column label="主机地址" prop="host" />
      <el-table-column label="端口" prop="port" width="100" />
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="描述" prop="description" show-overflow-tooltip />
      <el-table-column label="更新时间" prop="updateTime" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="服务器名称" required>
          <el-input v-model="formData.name" placeholder="请输入服务器名称" />
        </el-form-item>
        <el-form-item label="主机地址" required>
          <el-input v-model="formData.host" placeholder="请输入主机地址" />
        </el-form-item>
        <el-form-item label="端口" required>
          <el-input-number v-model="formData.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="用户名" required>
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.server-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-operations {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

